<template>
  <div class="login-container">
    <div class="form-container" :class="{ 'is-flipped': isFlipped }">
      <!-- 登录表单 -->
      <div class="form-box login">
        <h2>登录</h2>
        <el-form :model="loginForm" :rules="loginRules" ref="loginForm">
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              prefix-icon="el-icon-user"
              placeholder="请输入用户名">
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              prefix-icon="el-icon-lock"
              type="password"
              placeholder="请输入密码">
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha" class="captcha-container">
            <el-input 
              v-model="loginForm.captcha"
              prefix-icon="el-icon-picture"
              placeholder="请输入验证码"
              class="captcha-input">
            </el-input>
            <img 
              :src="captchaUrl" 
              class="captcha-img"
              @click="refreshCaptcha"
              alt="验证码"
              title="点击刷新验证码"
            />
          </el-form-item>
          <div class="form-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <a href="javascript:;" class="forget-pwd" @click="handleForgetPassword">忘记密码？</a>
          </div>
          <el-form-item>
            <el-button type="primary" @click="handleLogin" class="submit-btn">登录</el-button>
          </el-form-item>
        </el-form>
        <p class="switch-text">
          还没有账号？
          <a href="javascript:;" @click="flipCard">立即注册</a>
        </p>
      </div>

      <!-- 注册表单 -->
      <div class="form-box register">
        <h2>注册</h2>
        <el-form :model="registerForm" :rules="registerRules" ref="registerForm">
          <el-form-item prop="username">
            <el-input 
              v-model="registerForm.username" 
              prefix-icon="el-icon-user"
              placeholder="请输入用户名">
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              v-model="registerForm.password" 
              prefix-icon="el-icon-lock"
              type="password"
              placeholder="请输入密码">
            </el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input 
              v-model="registerForm.confirmPassword" 
              prefix-icon="el-icon-lock"
              type="password"
              placeholder="请确认密码">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleRegister" class="submit-btn">注册</el-button>
          </el-form-item>
        </el-form>
        <p class="switch-text">
          已有账号？
          <a href="javascript:;" @click="flipCard">返回登录</a>
        </p>
      </div>
    </div>

    <!-- 忘记密码对话框 -->
    <el-dialog
      title="忘记密码"
      :visible.sync="forgetDialogVisible"
      width="400px"
      center
      class="forget-dialog"
    >
      <el-form :model="forgetForm" :rules="forgetRules" ref="forgetForm" label-width="0">
        <el-form-item prop="email">
          <el-input 
            v-model="forgetForm.email"
            prefix-icon="el-icon-message"
            placeholder="请输入注册邮箱">
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha" class="captcha-container">
          <el-input 
            v-model="forgetForm.captcha"
            prefix-icon="el-icon-picture"
            placeholder="请输入验证码"
            class="captcha-input">
          </el-input>
          <img 
            :src="forgetCaptchaUrl" 
            class="captcha-img"
            @click="refreshForgetCaptcha"
            alt="验证码"
            title="点击刷新验证码"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="forgetDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleResetPassword">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword');
        }
        callback();
      }
    };
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (value === '') {
        callback(new Error('请输入邮箱'));
      } else if (!emailRegex.test(value)) {
        callback(new Error('请输入有效的邮箱地址'));
      } else {
        callback();
      }
    };

    return {
      isFlipped: false,
      loginForm: {
        username: '',
        password: '',
        captcha: ''
      },
      registerForm: {
        username: '',
        password: '',
        confirmPassword: ''
      },
      forgetForm: {
        email: '',
        captcha: ''
      },
      rememberMe: false,
      forgetDialogVisible: false,
      // 写死的验证码答案
      correctCaptcha: 'AB3C',
      correctForgetCaptcha: 'XY9Z',
      // 模拟验证码图片
      captchaUrl: '',
      forgetCaptchaUrl: '',
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePass, trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      },
      forgetRules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    };
  },
methods: {
    flipCard() {
      this.isFlipped = !this.isFlipped;
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          // 验证验证码
          if (this.loginForm.captcha.toUpperCase() !== this.correctCaptcha) {
            this.$message.error('验证码错误');
            this.refreshCaptcha();
            return false;
          }
          
          // 模拟登录成功
          localStorage.setItem('isLoggedIn', 'true');
          localStorage.setItem('username', this.loginForm.username);
          this.$message.success('登录成功');
          
          // 跳转到仪表板
          this.$router.push('/dashboard');
        } else {
          return false;
        }
      });
    },
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.$message.success('注册成功，请登录');
          this.isFlipped = false; // 切换到登录界面
        } else {
          return false;
        }
      });
    },
    handleForgetPassword() {
      this.forgetDialogVisible = true;
    },
    handleResetPassword() {
      this.$refs.forgetForm.validate((valid) => {
        if (valid) {
          // 验证验证码
          if (this.forgetForm.captcha.toUpperCase() !== this.correctForgetCaptcha) {
            this.$message.error('验证码错误');
            this.refreshForgetCaptcha();
            return false;
          }
          this.$message.success('重置密码邮件已发送到您的邮箱');
          this.forgetDialogVisible = false;
          this.forgetForm = { email: '', captcha: '' };
        } else {
          return false;
        }
      });
    },
    refreshCaptcha() {
      const codes = ['AB3C', 'XY9Z', 'MN7P', 'QR5T', 'UV8W'];
      this.correctCaptcha = codes[Math.floor(Math.random() * codes.length)];
      this.captchaUrl = `data:image/svg+xml;base64,${btoa(`<svg width="100" height="40" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="40" fill="#f5f5f5"/><text x="50" y="25" font-family="Arial" font-size="18" font-weight="bold" text-anchor="middle" fill="#333">${this.correctCaptcha}</text></svg>`)}`;
      this.loginForm.captcha = '';
    },
    refreshForgetCaptcha() {
      const codes = ['XY9Z', 'AB3C', 'CD6E', 'FG2H', 'IJ4K'];
      this.correctForgetCaptcha = codes[Math.floor(Math.random() * codes.length)];
      this.forgetCaptchaUrl = `data:image/svg+xml;base64,${btoa(`<svg width="100" height="40" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="40" fill="#f5f5f5"/><text x="50" y="25" font-family="Arial" font-size="18" font-weight="bold" text-anchor="middle" fill="#333">${this.correctForgetCaptcha}</text></svg>`)}`;
      this.forgetForm.captcha = '';
    }
  }
};
</script>

<style scoped>
.login-container {
  width: 100%;
  max-width: 400px;
  padding: 20px;
  perspective: 1000px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
}

.form-container {
  position: relative;
  width: 100%;
  height: 500px;
  transform-style: preserve-3d;
  transition: transform 0.8s;
}

.form-container.is-flipped {
  transform: rotateY(180deg);
}

.form-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  background: rgba(18, 18, 38, 0.5);
  border-radius: 10px;
  padding: 30px;
  box-sizing: border-box;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.form-box.login {
  transform: rotateY(0deg);
}

.form-box.register {
  transform: rotateY(180deg);
}

h2 {
  text-align: center;
  color: #fff;
  margin-bottom: 30px;
  font-size: 24px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  background: linear-gradient(45deg, #4FC3F7, #2196F3);
  border: none;
}

.submit-btn:hover {
  background: linear-gradient(45deg, #2196F3, #4FC3F7);
}

.switch-text {
  text-align: center;
  margin-top: 20px;
  color: #fff;
}

.switch-text a {
  color: #4FC3F7;
  text-decoration: none;
  margin-left: 5px;
  transition: color 0.3s ease;
}

.switch-text a:hover {
  color: #2196F3;
  text-decoration: none;
}

/* 验证码容器样式 */
.captcha-container >>> .el-form-item__content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  width: 33.33% !important;
  flex: none;
}

.captcha-img {
  width: 100px;
  height: 40px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.captcha-img:hover {
  border-color: #4FC3F7;
  transform: scale(1.05);
}

/* 表单选项样式 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.forget-pwd {
  color: #4FC3F7;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.3s ease;
}

.forget-pwd:hover {
  color: #2196F3;
  text-decoration: none;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-box {
  animation: fadeIn 0.5s ease-out;
}
</style>